

SERVER_CMD_HEADER = '@ServerCmd:'
CLIENT_CMD_HEADER = '@ClientCmd:'

#Command S -> C
CMD_S_LOGIN_OK   = 0x0001
CMD_S_LOGIN_FAIL = 0x0002
CMD_S_START      = 0x0003
CMD_S_STOP       = 0x0004

#Command C -> S
CMD_C_LOGIN    = 0x0001
CMD_C_NICKNAME = 0x0002
CMD_C_WANTCHAT = 0x0003
CMD_C_WNATLEAVE= 0x0004

'''
 Login
 ---------------------------------------------------
 1. Client -> Server
      CMD_C_LOGIN
 2. Client <- Server
      CMD_S_LOGIN_OK/CMD_S_LOGIN_FAIL
 
 options
 ---------------------------------------------------
 .. Client -> Server
      CMD_C_NICKNAME
 
 Chat Satrt
 ---------------------------------------------------
 3. Client -> Server
      CMD_C_WANTCHAT
 4. Client <- Server
      CMD_S_START
      
 Chat Stop
 ---------------------------------------------------
 ?. Client -> Server
      CMD_C_WNATLEAVE
 ?. Client <- Server
      CMD_S_STOP
 
 ---------------------------------------------------
'''




def EncodeCmd2Client(cmd):
    ''' Server Command format ex : @ServerCmd:0001\n '''
    return '%s%04x\n' % ( SERVER_CMD_HEADER, cmd )

def DecodeCmdFromClient(cmd):
    ''' Client Command format ex : @ClientCmd:0001\n '''
    if cmd[-1] != '\n':
        return -1
    if cmd.startswith(CLIENT_CMD_HEADER):
        return eval('0x' + cmd.split(':')[1].strip())
    return -1
    
    

def EncodeCmd2Server(cmd):
    return '%s%04x\n' % ( CLIENT_CMD_HEADER, cmd )

def DecodeCmdFromServer(cmd):
    if cmd[-1] != '\n':
        return -1
    if cmd.startswith(SERVER_CMD_HEADER):
        return eval('0x' + cmd.split(':')[1].strip())
    return -1
    


BUFSIZ = 1024
class SocketAgent(object):
    def __init__(self, socket = None):
        super(SocketAgent, self).__init__()
        self.socket = socket
        self.rmsg = ''
    
    @property
    def fno(self):
        return self.socket.fileno()
    
    def sendmsg(self, msg):
        count = len(msg)
        while count > 0:
            count -= self.socket.send( msg[len(msg)-count:] )
        
    def recvline(self, includeNewLine=False):
        idx = self.rmsg.find('\n')
        if idx > 0:
            msg = self.rmsg[:idx]
            if includeNewLine: msg.join('\n');
            self.rmsg = self.rmsg[idx+1:]
            return msg
        
        while True:
            data = self.socket.recv(BUFSIZ)
            if data == '':
                raise RuntimeError("socket connection broken")
            
            self.rmsg += data
            msg = ''
            for i, c in enumerate(self.rmsg):
                if c == '\n':
                    if i == len(self.rmsg)-1:
                        self.rmsg = ''
                    else:
                        self.rmsg = self.rmsg[i:]
                    
                    if includeNewLine: msg+=c;
                    
                    return msg
                else:
                    msg += c
        return -1
    